<script lang="ts" setup>
import type { ForgetPasswordInformationProps } from '@croco/framework/libraries';

import { ref } from 'vue';

import { AuthenticationForgetPassword } from '@croco/framework/libraries';
import { $t } from '@croco/framework/locales';

import VForgetPasswordForm from '#/bean/forget-password-form.vue';

defineOptions({ name: 'ForgetPassword' });

const loading = ref(false);

const forgetPasswordFormRef = ref<InstanceType<typeof VForgetPasswordForm>>();
const form = ref<ForgetPasswordInformationProps>({
    mobile: undefined,
    email: undefined,
    password: undefined,
    code: undefined,
});
const rules = ref({
    mobile: [
        { required: true, message: $t('authentication.mobileTip'), trigger: 'blur' },
        { pattern: /^1(3\d|4[014-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/, message: $t('authentication.mobileErrortip'), trigger: 'blur' },
    ],
    email: [
        { required: true, message: $t('authentication.emailTip'), trigger: 'blur' },
        { pattern: /^[\w.%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i, message: $t('authentication.emailValidErrorTip'), trigger: 'blur' },
    ],
    code: [{ required: true, message: $t('authentication.codeTip'), trigger: 'blur' }],
    password: [{ required: true, message: $t('authentication.passwordTip'), trigger: 'blur' }],
});

async function handleSubmit(steps: number): Promise<boolean> {
    return await forgetPasswordFormRef.value?.validate((status) => {
        if (status) {
            loading.value = true;
            if (steps === 1) {
                // todo 校验邮箱号/手机号跟验证码是否匹配
                console.warn('Send...');
            } else if (steps === 2) {
                // todo 重置密码
                console.warn('Send...');
            }
        }
        return status;
    });
}

function handleSend(data: ForgetPasswordInformationProps) {
    // todo 通过电子邮箱/手机号码发送验证
    console.warn(data);
}
</script>

<template>
    <AuthenticationForgetPassword :max-steps="3" :submit="handleSubmit" :loading="loading">
        <template #default="{ active }">
            <VForgetPasswordForm ref="forgetPasswordFormRef" v-model="form" :active="active" :rules="rules" @send="handleSend" />
        </template>
    </AuthenticationForgetPassword>
</template>
